package events

import (
	"encoding/json"
	"time"

	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/google/uuid"
)

// OrderCreated 订单创建事件结构体
// OrderID: 订单ID
// UserID: 用户ID
// Items: 订单商品列表
// Total: 订单总价
// CreatedAt: 事件创建时间
type OrderCreated struct {
	OrderID   string    `json:"order_id"`
	UserID    string    `json:"user_id"`
	Items     []Item    `json:"items"`
	Total     float64   `json:"total"`
	CreatedAt time.Time `json:"created_at"`
}

// Item 商品结构体
// SKU: 商品编号
// Qty: 商品数量
type Item struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

// InventoryReserved 库存预留事件结构体
// OrderID: 订单ID
// ReservedAt: 库存预留时间
type InventoryReserved struct {
	OrderID    string    `json:"order_id"`
	ReservedAt time.Time `json:"reserved_at"`
}

// NewOrderCreated 构造订单创建事件
func NewOrderCreated(orderID, userID string, items []Item, total float64) OrderCreated {
	return OrderCreated{
		OrderID:   orderID,
		UserID:    userID,
		Items:     items,
		Total:     total,
		CreatedAt: time.Now().UTC(),
	}
}

// EncodeOrderCreated 编码订单创建事件为 Watermill 消息
func EncodeOrderCreated(evt OrderCreated) (*message.Message, error) {
	payload, err := json.Marshal(evt)
	if err != nil {
		return nil, err
	}
	msg := message.NewMessage(uuid.NewString(), payload)
	msg.Metadata.Set("event_type", "OrderCreated")
	return msg, nil
}

// EncodeInventoryReserved 编码库存预留事件为 Watermill 消息
func EncodeInventoryReserved(evt InventoryReserved) (*message.Message, error) {
	payload, err := json.Marshal(evt)
	if err != nil {
		return nil, err
	}
	msg := message.NewMessage(uuid.NewString(), payload)
	msg.Metadata.Set("event_type", "InventoryReserved")
	return msg, nil
}
